import 'dart:async';
import 'dart:convert';

import 'package:alipay_kit/alipay_kit.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyLogger.dart';
import 'package:flutter/material.dart';

import '../../constant/EcyEventConsnt.dart';
import '../EcyEventBus.dart';
import 'EcyStorage.dart';

class EcyAlipayUtil {
  static const bool _ALIPAY_USE_RSA2 = true;
  static const String _ALIPAY_APPID = 'your alipay appId'; // 支付/登录
  static const String _ALIPAY_PID = 'your alipay pid'; // 登录
  static const String _ALIPAY_TARGETID = 'your alipay targetId'; // 登录
  static const String _ALIPAY_PRIVATEKEY =
      'your alipay rsa private key(pkcs1/pkcs8)'; // 支付/登录

  StreamSubscription<AlipayResp>? _paySubs;
  StreamSubscription<AlipayResp>? _authSubs;

  factory EcyAlipayUtil() => _instance;
  static late final EcyAlipayUtil _instance = EcyAlipayUtil._internal();
  late BuildContext context;
  EcyAlipayUtil._internal() {
    EcyLogger.log("EcyAlipayUtil init");
    init();
  }

  init() {
    _paySubs ??= AlipayKitPlatform.instance.payResp().listen(_listenPay);
    _authSubs ??= AlipayKitPlatform.instance.authResp().listen(_listenAuth);
  }

  void _listenPay(AlipayResp resp) {
    final String content = 'pay: ${resp.resultStatus} - ${resp.result}';
    EcyStorage.getString(EcyEventConst.kPayedOrderId).then((orderId) {
      EcyRouter.pushReplacement(this.context, EcyRouter.orderInfoPage, orderId);
    }).catchError((onError) {
      EcyRouter.pushReplacement(this.context, EcyRouter.orderInfoPage, "");
    });
    EcyEventBus().emit(EcyEventConst.kPaySuccess);
    EcyEventBus().emit(EcyEventConst.kOnOrder);
    EcyLogger.log("_listenPay:" + content);
  }

  void _listenAuth(AlipayResp resp) {
    final String content = 'pay: ${resp.resultStatus} - ${resp.result}';
    EcyLogger.log("_listenAuth:" + content);
  }

  checkPayEnv() async {
    final String content =
        'alipay: ${await AlipayKitPlatform.instance.isInstalled()}';
  }

  startPay(String _orderInfo, BuildContext context) {
    this.context = context;
    AlipayKitPlatform.instance.pay(orderInfo: _orderInfo);
  }
}
